<template>
    <div class="countdown">
      {{ formattedTime }}
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onBeforeUnmount, watch, computed } from 'vue'
  
  const props = defineProps({
    time: {
      type: String,
      required: true
    },
    mode: {
      type: String,
      default: 'countdown',
      validator: (val) => ['countdown', 'timer'].includes(val)
    }
  })
  
  const emit = defineEmits(['done'])
  
  const totalSeconds = ref(0)
  let timer = null

  const formattedTime = computed(() => {
    const minutes = Math.floor(totalSeconds.value / 60)
    const seconds = totalSeconds.value % 60
    return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
  })
  

  function parseTimeString(str) {
    const h = parseInt(str.match(/(\d+)\s*小时/)?.[1] || 0)
    const m = parseInt(str.match(/(\d+)\s*分/)?.[1] || 0)
    const s = parseInt(str.match(/(\d+)\s*秒/)?.[1] || 0)

    return h * 3600 + m * 60  + s
  }

  function startTimer() {
    clearInterval(timer)
    totalSeconds.value = parseTimeString(props.time)
  
    timer = setInterval(() => {
      if (props.mode === 'countdown') {
        if (totalSeconds.value > 0) {
          totalSeconds.value--
        } else {
          clearInterval(timer)
          emit('done')
        }
      } else {
        totalSeconds.value++
      }
    }, 1000)
  }
  

  onMounted(startTimer)
  onBeforeUnmount(() => clearInterval(timer))
  
  watch(() => props.time, startTimer)
  watch(() => props.mode, startTimer)
  </script>
  
  <style scoped>
  .countdown {
    margin-left: 5px;
  }
  </style>
  
  